﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SudokuGame.Sudoku
{
    /// <summary>
    /// 混沌随机数扩展
    /// </summary>
    public class ChaosRandomEx
    {
        private readonly ChaosRandom _chaosRandom;
        /// <summary>
        /// 默认u=4
        /// </summary>
        public ChaosRandomEx() : this(4f)
        {
        }
        /// <summary>
        /// u=[0,4]
        /// u=4 完全混沌
        /// </summary>
        /// <param name="u"></param>
        public ChaosRandomEx(float u)
        {
            _chaosRandom = new ChaosRandom(u);
        }
        public int Next(int up)
        {
            return Next(0, up);
        }
        public int Next(int low, int up)
        {
            if (up <= low)
                throw new Exception("up必须大于low");

            return (int)Math.Round(_chaosRandom.GetRandom() * (up - low) + low, 0);
        }
        public double NextDouble()
        {
            return _chaosRandom.GetRandom();
        }
        public double NextDouble(double up)
        {
            return NextDouble(0, up);
        }
        public double NextDouble(double low, double up)
        {
            if (up <= low)
                throw new Exception("up必须大于low");

            return _chaosRandom.GetRandom() * (up - low) + low;
        }
    }
    /// <summary>
    /// 基于Logistic混沌模型
    /// 若μ∈[3.57,4]，则该系统处于混沌态；若μ＝４，系统处于完全混沌状态。一般取μ为4。
    /// </summary>
    public class ChaosRandom
    {
        private readonly Random _rand;
        private double _prevRandom;
        private float _u;
        /// <summary>
        /// 默认u=4
        /// </summary>
        public ChaosRandom() : this(4f)
        {
        }
        /// <summary>
        /// u=[0,4]
        /// u=4 完全混沌
        /// </summary>
        /// <param name="u"></param>
        public ChaosRandom(float u)
        {
            if (u < 0)
                u = 0;
            if (u > 4)
                u = 4;

            _rand = new Random();
            _prevRandom = Double.MinValue;
            _u = u;
        }
        public double GetRandom()
        {
            return CreationRandom();
        }
        private double CreationRandom()
        {
            if (_prevRandom == Double.MinValue)
                _prevRandom = _rand.NextDouble();
            else
                _prevRandom = _prevRandom * _u * (1 - _prevRandom);

            return _prevRandom;
        }
    }
}
